package com.ljx.funchat.chat.service.strategy;

import com.ljx.funchat.chat.dao.MessageDao;
import com.ljx.funchat.chat.dao.RedbagDao;
import com.ljx.funchat.chat.dao.RedbagRecordDao;
import com.ljx.funchat.chat.domain.entity.Message;
import com.ljx.funchat.chat.domain.entity.msg.MessageExtra;
import com.ljx.funchat.chat.domain.entity.msg.RedBagMsgDTO;
import com.ljx.funchat.chat.domain.enums.MessageTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

/**
 * 红包消息
 */
@Component
public class RedbagMsgHandler extends AbstractMsgHandler<RedBagMsgDTO> {

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private RedbagDao redbagDao;

    @Autowired
    private RedbagRecordDao redbagRecordDao;

    @Override
    MessageTypeEnum getMsgTypeEnum() {
        return MessageTypeEnum.REDBAG;
    }

    @Override
    protected void checkMsg(RedBagMsgDTO body, Long roomId, Long uid) {

    }

    @Override
    public void saveMsg(Message msg, RedBagMsgDTO body) {
        // 插入文本内容
        MessageExtra extra = Optional.ofNullable(msg.getExtra()).orElse(new MessageExtra());
        // 进一步更新消息
        Message update = new Message();
        update.setId(msg.getId());
        update.setContent("[红包消息]" + body.getDesc());
        extra.setRedBagMsgDTO(body);
        update.setExtra(extra);
        // 更新消息
        messageDao.updateById(update);
        // 更新红包消息ID
        redbagDao.updateMsgIdById(body.getRedbagId(), msg.getId());
    }

    @Override
    public Object showMsg(Message msg, Long uid) {
        RedBagMsgDTO redBagMsgDTO = msg.getExtra().getRedBagMsgDTO();
        Long redbagId = redBagMsgDTO.getRedbagId();
        // 是否领取
        Integer count = redbagRecordDao.countByUidAndRedbagId(uid, redbagId);
        redBagMsgDTO.setObtain(Objects.nonNull(count) && count > 0);
        return msg.getExtra().getRedBagMsgDTO();
    }

    @Override
    public Object showReplyMsg(Message msg) {
        return msg.getContent();
    }

    @Override
    public String showContactMsg(Message msg) {
        return msg.getContent();
    }
}
